<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="formData.customerName"
          placeholder="请输入客户名称"
        />
      </el-form-item>
      <el-form-item label="客户等级" prop="customerLevel">
        <el-select
          v-model="formData.customerLevel"
          placeholder="请选择客户等级"
        >
          <el-option label="普通客户" value="1" />
          <el-option label="VIP客户" value="2" />
          <el-option label="白金客户" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, inject } from "vue";

defineOptions({ name: "CustomerForm" });

const { t } = useI18n();
const message = useMessage();

const dialogVisible = ref(false);
const dialogTitle = ref("");
const formLoading = ref(false);
const formType = ref("");
const formData = ref({
  id: undefined,
  customerName: undefined,
  customerLevel: undefined,
  phone: undefined,
  createTime: undefined,
});

const formRules = reactive({
  customerName: [
    { required: true, message: "客户名称不能为空", trigger: "blur" },
  ],
  customerLevel: [
    { required: true, message: "请选择客户等级", trigger: "change" },
  ],
  phone: [{ required: true, message: "联系电话不能为空", trigger: "blur" }],
});

const formRef = ref();

// 关键修改1：确保open方法被正确定义和暴露
const open = (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();

  if (id) {
    formLoading.value = true;
    try {
      const getCustomerById = inject("getCustomerById") as (id: number) => any;
      if (getCustomerById) {
        const customer = getCustomerById(id);
        if (customer) {
          formData.value = JSON.parse(JSON.stringify(customer));
        }
      }
    } finally {
      formLoading.value = false;
    }
  }
};

// 关键修改2：确保正确暴露方法
defineExpose({ open });

const submitForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    formLoading.value = true;

    if (formType.value === "create") {
      const addCustomer = inject("addCustomer") as (customer: any) => void;
      if (addCustomer) {
        const newCustomer = {
          ...formData.value,
          id: Date.now(),
          createTime: new Date().toISOString(),
        };
        addCustomer(newCustomer);
        message.success(t("common.createSuccess"));
      }
    } else {
      const updateCustomer = inject("updateCustomer") as (
        customer: any
      ) => void;
      if (updateCustomer) {
        updateCustomer(formData.value);
        message.success(t("common.updateSuccess"));
      }
    }

    dialogVisible.value = false;
    emit("success");
  } finally {
    formLoading.value = false;
  }
};

const resetForm = () => {
  formData.value = {
    id: undefined,
    customerName: undefined,
    customerLevel: undefined,
    phone: undefined,
    createTime: undefined,
  };
  formRef.value?.resetFields();
};

const emit = defineEmits(["success"]);
</script>
